package com.example.finalframe.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.example.finalframe.service.intf.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;


@Slf4j
@Service
@ConditionalOnProperty(name = "files.storage.type", havingValue = "local")
public class LocalFileServiceImpl implements FileService {
    //本地存储实现
    //文件磁盘路径
    @Value("${files.upload.path}")
    private String fileUploadPath;
    @Override
    public String storeFile(MultipartFile file) {
        //获取文件原始名称
        String originalFilename = file.getOriginalFilename();
        //获取文件的类
        String type = FileUtil.extName(originalFilename);
        log.info("文件类型是：" + type);
        //获取文件大小
        long size = file.getSize();

        //获取文件
        File uploadParentFile = new File(fileUploadPath);
        //判断文件目录是否存在
        if(!uploadParentFile.exists()) {
            //如果不存在就创建文件夹
            uploadParentFile.mkdirs();
        }
        //定义一个文件唯一标识码（UUID）
        String uuid = UUID.randomUUID().toString();

        File uploadFile = new File(fileUploadPath + uuid + StrUtil.DOT + type);
        //将临时文件转存到指定磁盘位置
        try {
            file.transferTo(uploadFile);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return "SUCCESS";
    }
}
